python读取文件之前判断文件编码格式 |
您所在的位置:网站首页 › python read csv utf-8 › python读取文件之前判断文件编码格式 |
困扰
经常用pandas读取csv格式文件,pandas默认使用utf-8编码格式,但有的文件并非这种编码,虽然可以通过记事本打开文件,然后另存为,通过保存格式为utf-8格式,但是这种方式实在是太麻烦太傻,如图1 手动查看编码格式。 通过代码自动判断类型,写一个get_encoding函数 def get_encoding(file): with open(file,'rb') as f: tmp = chardet.detect(f.read()) return tmp['encoding']正常运行需要导入chardet包 import chardet代码中chardet.detect输入文件内容,返回要给字典,通过字典键‘encoding’获取编码值,如果文件很大,建议输入为f.read(2)就行,读入前5行内容作为输入即可 效果 if __name__ == '__main__': fpath = "D:\\异常检测\\nab\\realAWSCloudwatch\\realAWSCloudwatch" fname = "\\ec2_cpu_utilization_825cc2.csv" fullPath = fpath + fname encoding = get_encoding(fullPath) print(encoding) data = pd.read_csv(fullPath, encoding = encoding) print(data.head(2))结果 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |